import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpEchoClient {
    DatagramSocket socket = null;
    //客户端要知道服务器的IP地址和端口号,客户端不需要绑定端口号,系统会默认分配
    private String serverIp;
    private int serverPort;
    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
        this.socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }
    //客户端启动逻辑
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true){
            //先从控制台读取字符串
            System.out.println(":>");
            String request = scanner.next();
            //通过获取服务器的ip地址和端口号把字符串构造成数据报发送出去,
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(serverIp),serverPort);
            //通过网卡发送
            socket.send(requestPacket);
            //接收客户端的数据并填充到构造好的容器当中
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //把响应数据转换成 String 显示出来.
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.printf("req: %s, resp: %s\n", request, response);
        }
    }
    //启动客户端
    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
